//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.qst.crop.controller;

import com.qst.crop.common.Result;
import com.qst.crop.entity.IOTDeviceMessage;
import com.qst.crop.entity.Site;
import com.qst.crop.service.IOTDeviceMessageService;
import com.qst.crop.service.SiteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping({"/site"})
@CrossOrigin
@Api(
        tags = {"种植场地模块接口"}
)
public class SiteController {
    @Autowired
    SiteService service;
    @Autowired
    IOTDeviceMessageService iotDeviceMessageService;

    public SiteController() {
    }

    @ApiOperation("生产场地查询")
    @GetMapping({"/list"})
    public List<Site> getList() {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        return this.service.getSiteList(name);
    }

    @ApiOperation("生产场地新增")
    @PostMapping({"/insert"})
    public Result insert(@RequestBody Site site) {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        site.setUserName(name);
        if (site.getIotDeviceId() != null && !site.getIotDeviceId().equals("")) {
            IOTDeviceMessage message = this.iotDeviceMessageService.getByCode(site.getIotDeviceId());
            if (message == null) {
                return new Result(false, 20001, "设备码错误，请检查设备码");
            }
        }

        this.service.insertSite(site);
        return new Result(true, 20000, "添加成功");
    }

    @ApiOperation("生产场地修改")
    @PutMapping({"/update"})
    public Result update(@RequestBody Site site) {
        this.service.updateSite(site);
        return new Result(true, 20000, "修改成功");
    }

    @ApiOperation("生产场地删除")
    @DeleteMapping({"/delete/{id}"})
    public Result delete(@PathVariable("id") Integer id) {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        this.service.getSiteList(name);
        this.service.deleteSite(id);
        return new Result(true, 20000, "删除成功");
    }
}
